package com.kk.crowd.controller;

import com.kk.crowd.api.MySQLRemoteService;
import com.kk.crowd.api.RedisRemoteService;
import com.kk.crowd.constant.CrowdConstant;
import com.kk.crowd.entity.po.MemberPO;
import com.kk.crowd.entity.vo.MemberLoginVO;
import com.kk.crowd.entity.vo.MemberVO;
import com.kk.crowd.util.CrowdUtil;
import com.kk.crowd.util.ResultEntity;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

@Controller
public class MemberController {

    @Autowired
    private RedisRemoteService redisRemoteService;

    @Autowired
    private MySQLRemoteService mySQLRemoteService;

    /**
     * 短信验证码
     * @param phone
     * @return
     */
    @RequestMapping("/member/auth/sendShortMessage")
    @ResponseBody
    public ResultEntity<String> sendShortMessage(@RequestParam("phone") String phone){
        //  发送短信
        ResultEntity<String> resultEntity = CrowdUtil.sendCodeByShortMessage(phone);
        //  如果短信发送失败
        if (ResultEntity.FAILED.equals(resultEntity.getOperationResult())){
            return resultEntity;
        }

        //  发送成功
        //  获取发送的验证码
        String checkCode = resultEntity.getQueryData();
        String key = CrowdConstant.REDIS_CODE_PREFIX + phone;
        //  将验证码存入redis
        ResultEntity<String> redisResult = redisRemoteService.setRedisKeyValueRemoteWithTimeout(key, checkCode, 15, TimeUnit.MINUTES);
        if (ResultEntity.SUCCESS.equals(redisResult.getOperationResult())){
            return ResultEntity.successWithData(checkCode);
        }else {
            return redisResult;
        }
    }

    /**
     * 会员注册
     * @param memberVO
     * @param modelMap
     * @return
     */
    @RequestMapping("/member/auth/do/register")
    public String register(MemberVO memberVO, ModelMap modelMap){
        //  1、获取用户输入的手机号
        String phone = memberVO.getPhone();
        //  2、拼接redis查询所需的key
        String key = CrowdConstant.REDIS_CODE_PREFIX + phone;
        //  3、从redis查询出验证码
        ResultEntity<String> result = redisRemoteService.getRedisStringValueByKeyRemote(key);
        //  如果redis查询失败
        if (ResultEntity.FAILED.equals(result.getOperationResult())){
            modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,CrowdConstant.ERROR_NOSQL_CAN_NOT_CONNECT);
            return "member-reg";
        }
        //  如果没有查到该验证码
        if (ResultEntity.SUCCESS.equals(result.getOperationResult()) && result.getQueryData()==null){
            modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,"验证码不存在");
            return "member-reg";
        }

        //  查到验证码了
        String code = result.getQueryData();

        //  4、如果验证码和用户输入的不一致
        if (code!=null && !code.equals(memberVO.getCode())){
            modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,CrowdConstant.ERROR_VERIFICATION_CODE_IS_NOT_EQUAL);
            return "member-reg";
        }else{
            //  5、验证码一致
            //  6、删除redis中的验证码
            redisRemoteService.removeRedisKeyRemote(key);
            //  7、密码加密
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            memberVO.setUserpswd(passwordEncoder.encode(memberVO.getUserpswd()));
            //  8、执行保存
            MemberPO memberPO = new MemberPO();
            BeanUtils.copyProperties(memberVO,memberPO);
            ResultEntity<String> saveMemberResultEntity = mySQLRemoteService.saveMemberRemote(memberPO);
            if (ResultEntity.FAILED.equals(saveMemberResultEntity.getOperationResult())){
                modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,saveMemberResultEntity.getOperationMessage());
                return "member-reg";
            }
            //  9、跳转登录页面
            return "redirect:/member/auth/to/login/page";
        }
    }

    /**
     * 会员登录
     * @return
     */
    @RequestMapping("/member/auth/do/login")
    public String login(@RequestParam("loginacct") String loginacct,
                        @RequestParam("userpswd") String userpswd,
                        ModelMap modelMap,
                        HttpSession session){
        //  1、根据loginacct查询MemberPO
        ResultEntity<MemberPO> result = mySQLRemoteService.getMemberPOByLoginAcctRemote(loginacct);

        //  如果查询失败
        if (ResultEntity.FAILED.equals(result.getOperationResult())){
            modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,"查询失败");
            return "member-login";
        }

        //  查询成功，但没有数据
        MemberPO memberPO = result.getQueryData();
        if (memberPO==null){
            modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,"查询成功，但没数据");
            return "member-login";
        }

        //  2、查询出了memberPO，比较密码
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String beforeEncode = userpswd;
        String afterEncode = bCryptPasswordEncoder.encode(beforeEncode);
        boolean isSame = bCryptPasswordEncoder.matches(beforeEncode, memberPO.getUserpswd());
        //  如果相等
        if (isSame){
            MemberLoginVO memberLoginVO = new MemberLoginVO();
            BeanUtils.copyProperties(memberPO,memberLoginVO);
            //  将memberLoginVO存入session
            session.setAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER,memberLoginVO);
            //  重定向到首页
//            return "redirect:/member/auth/to/center/page";
            return "redirect:" + CrowdConstant.ATTR_NAME_ZUUL + "/member/auth/to/center/page";
        }else {
            //  如果不等,转发到登录页面。
            modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,"账号密码错误！");
            return "member-login";
        }
    }

    @RequestMapping("/member/auth/do/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "redirect:/";
    }
}
